package com.example.onlinetaxi.ui.activity.DriverToStartPage;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.DriverGetCancelThread;
import com.example.onlinetaxi.callback.DriverCallBack.ICancelDrive;
import com.example.onlinetaxi.callback.DriverCallBack.IStartDrive;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.view.Dialog.MyDialog;
import com.example.onlinetaxi.view.Dialog.PhoneDialog;

import java.util.HashMap;
import java.util.Map;

public class DriverGoingFragment extends Fragment {
    private View rootView;

    private Button haveBeenReached;
    // 接口
    private IStartDrive iStartDrive;
    // 请求参数
    private Map<String, String> map = new HashMap<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_driver_going, container, false);

        initView();

        initEvent();

        if (DriverGetCancelThread.thread == null) {
            // 司机启动线程，监视订单状态，以防乘客取消
            DriverGetCancelThread.iCancelDrive = new ICancelDrive() {
                @Override
                public void cancelDrive(String cancelReason) {
                    // 弹出确认对话框
                    showCancelDialog(cancelReason);
                }
            };
            DriverGetCancelThread.finished = false;
            DriverGetCancelThread.thread = new Thread(new DriverGetCancelThread.GetOrderState());
            DriverGetCancelThread.thread.start();
        }

        return rootView;
    }


    private void initEvent() {
        haveBeenReached.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 展示输入尾号的对话框
                showDialog();
            }
        });
    }

    private void showDialog() {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 不进行操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取司机输入
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(PhoneDialog.Builder.num_in1_et.getText());
                stringBuffer.append(PhoneDialog.Builder.num_in2_et.getText());
                stringBuffer.append(PhoneDialog.Builder.num_in3_et.getText());
                stringBuffer.append(PhoneDialog.Builder.num_in4_et.getText());

                // 验证司机输入是否正确
                if (verifyPhone_4(stringBuffer.toString())) {
                    // 销毁司机启动线程
                    DriverGetCancelThread.finished = true;
                    DriverGetCancelThread.thread = null;
                    DriverGetCancelThread.iCancelDrive = null;

                    // 跳转到司机前往界面，通过回调函数实现
                    iStartDrive.startDrive();
                }
            }
        };

        // 显示提示框
        PhoneDialog.showInfoDialog(getActivity(), onCancelClickListener, onConfirmClickListener);
    }

    private void showCancelDialog(String cancelReason) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 拒绝用户的请求
                disagree();

                // 重新启动线程
                DriverGetCancelThread.thread = new Thread(new DriverGetCancelThread.GetOrderState());
                DriverGetCancelThread.thread.start();
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 同意用户的请求
                agree();
            }
        };

        if (cancelReason.equals("")) {
            cancelReason = "无";
        }

        // 显示提示框
        Looper.prepare();
        MyDialog.drawable = getActivity().getApplicationContext().getDrawable(R.drawable.dialog_confirm_driver);
        MyDialog.showInfoDialog(getActivity(), "用户申请取消订单，理由:" + cancelReason, "拒绝", onCancelClickListener, "同意", onConfirmClickListener);
        Looper.loop();
    }

    private void agree() {
        map.clear();
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());
        map.put("cancelState", "2");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "setDriverCancel");

        // 关闭线程
        DriverGetCancelThread.finished = false;
        DriverGetCancelThread.thread = null;

        // 删除保存本地的订单数据
        LocalStorage.chosenOrder = null;
        LocalStorage.currentOrderId = null;
        LocalStorage.currentOrder = null;

        getActivity().finish();

    }

    private void disagree() {
        map.clear();
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());
        map.put("cancelState", "3");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "setDriverCancel");

        // 关闭线程
        DriverGetCancelThread.finished = false;
        DriverGetCancelThread.thread = null;

    }

    private boolean verifyPhone_4(String phone_4) {
        // 将后四位手机号发送到后台，验证手机号
        map.clear();
        map.put("phone_4", phone_4);
        map.put("orderId", LocalStorage.currentOrderId);

        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "verifyPhone_4");
        // 获取响应体
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);

        if (dataResponse.getCode().equals("200")) {
            return true;
        } else {
            Toast.makeText(getActivity(), dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void initView() {
        haveBeenReached = rootView.findViewById(R.id.have_been_received_going);
    }

    public void setiStartDrive(IStartDrive iStartDrive) {
        this.iStartDrive = iStartDrive;
    }
}